package com.zyq.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Verification;

import java.util.*;

public class JWTUtil {
    // 设置秘钥，不可以透露
    private static final String sign = "aaa";

    // 1. 生成token
    public static String createToken(Map<String, Object> map){
        // 设置头
        Map<String, Object> head = new HashMap<>();
        head.put("typ","Jwt");
        head.put("alg","HS156");
        // 颁布时间
        Date date = new Date();
        // 过期时间 先获取当前时间
        Calendar expire = Calendar.getInstance();
        expire.set(Calendar.SECOND,7200);
        Date expireTime = expire.getTime();

        String token = JWT.create()
                // 头部
                .withHeader(head)
                // 颁布时间
                .withIssuedAt(date)
                // 过期时间
                .withExpiresAt(expireTime)
                // 自定义内容
                .withClaim("userInfo", map)
                // 签名
                .sign(Algorithm.HMAC256(sign));
        return token;
    }
    // 2. 校验token
    public static boolean verifyToken(String token){
        // 1. 先拿到这个token
        JWTVerifier build = JWT.require(Algorithm.HMAC256(sign)).build();
        try{
            DecodedJWT verify = build.verify(token);
            return true;
        }catch (Exception e){
            System.out.println("token无效");
            return false;
        }

    }
    // 3. 获取token当中的登录信息
    public static Map<String,Object> getTokenChaim(String token){
        JWTVerifier build = JWT.require(Algorithm.HMAC256(sign)).build();
        DecodedJWT verify = build.verify(token);
        Claim userInfo = verify.getClaim("userInfo");
        return userInfo.asMap();
    }
}
